<template>
  <div class="dialog">
    <el-dialog title='添加检验报告' :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="选择批次：" class="w50p" prop="productionBatchDTO">
          <el-select filterable clearable v-model="formData.productionBatchDTO" value-key="productionBatchId" clearable filterable
            @change="batchChange">
            <el-option v-for="batchitem in batchList" :key="batchitem.productionBatchId" :label="batchitem.mnecode"
              :value="batchitem" />
          </el-select>
        </el-form-item>
        <el-form-item label="检验人：" class="w50p" prop="staffName">
          <el-select filterable clearable disabled v-model="formData.staffName" clearable filterable placeholder="请选择检验人">
            <el-option v-for="item in staffList" :key="item.staffId" :label="item.staffName" :value="item.staffId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验类型：" class="w50p" prop="checkType">
          <el-select filterable clearable v-model="formData.checkType" clearable placeholder="请选择">
            <el-option label="入场检" value="ENTRYINSPECTION"> </el-option>
            <el-option label="过程检" value="PROCESSINSPECTION"> </el-option>
            <el-option label="成品检" value="FINISHEDPRODUCTINSPECTION"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验名称：" class="w50p" prop="checkName">
          <el-input v-model="formData.checkName" clearable placeholder="请输入检验名称" />
        </el-form-item>
        <el-form-item label="是否正常：" class="w50p" prop="whetherNormal">
          <el-select filterable clearable v-model="formData.whetherNormal" clearable placeholder="请选择">
            <el-option label="是" :value="true"> </el-option>
            <el-option label="否" :value="false"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验时间：" class="w50p" prop="uploadDateTime">
          <el-date-picker v-model="formData.uploadDateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" clearable
            placeholder="选择日期时间" default-time="12:00:00" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="填写检验说明：" class="w50p" prop="remark">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="formData.remark">
          </el-input>
        </el-form-item>
        <el-form-item label="上传文件：" class="w50p" prop="reportFileIdList">
          <el-upload class="upload-demo" ref="uploadFile" action="" :on-change="handleFileChange"
            :on-remove="handleRemove" :file-list="fileList" accept=".png,.jpg,.jpeg,.doc,.docx,.pdf,.txt,.excel"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.png,.jpg,.jpeg,.doc,.docx,.pdf,.txt,.excel文件,且不能超过5MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MultipleUploadMany from "@/components/uploadimage/MultipleUploadMany.vue"
import inspectionReportApi from "@/api/inspection-management/inspection-report-management";
import StaffApi from "@/api/basic-info-manage/staff"; //员工
import BatchApi from "@/api/batch-mange/index"; //批次
import demoApi from "@/api/document"; //文件
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: '',
  components: { MultipleUploadMany },
  mixins: [dialogMixin],
  props: {
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    batchList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      fileList: [],//文件列表
      showDialog: this.show, //弹窗显隐
      formData: {  //表单
        checkName: '', //检验名称
        remark: '', //检验说明
        checkType: '',//检验类型
        staffName: '', //检验人
        whetherNormal: '', //是否合格
        uploadDateTime: '', //检验时间
        productionBatchId: '',//批次id
        reportFileIdList: [], //文件列表
      },
      rules: {
        productionBatchDTO: [
          { required: true, message: "请选择批次", trigger: "change" }
        ],
        checkName: [
          { required: true, message: "请输入检验名称", trigger: "change" }
        ],
        remark: [
          { required: true, message: "请输入检验说明", trigger: "change" }
        ],
        checkType: [
          { required: true, message: "请输入检验类型", trigger: "change" }
        ],
        staffName: [
          { required: true, message: "请选择检验人", trigger: "change" }
        ],
        whetherNormal: [
          { required: true, message: "请选择是否合格", trigger: "change" }
        ],
        uploadDateTime: [
          { required: true, message: "请选择检验时间", trigger: "change" }
        ],
      }
    };
  },
  watch: {
    show (v) {
      maxTime = null
      this.showDialog = v;
      // this.formData = JSON.parse(JSON.stringify(this.editObject))
      this.fileList = []
    },
    nowChanceStau (v) {
      if (v === 'add') {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
        }
        this.$set(this.formData, 'uploadDateTime', this.formatDateTimeMHS(new Date()))
      }
    }
  },
  created () {
    maxTime = null
  },
  methods: {
    batchChange (e) {
      maxTime = ''
      this.formData.uploadDateTime = this.formatDateTimeMHS(new Date())
      this.batchList.find(item => {
        if (item.productionBatchId === e.productionBatchId) {
          this.buildDateTime = new Date(item.buildDateTime)
          maxTime = new Date(this.buildDateTime)
          // this.formData.uploadDateTime = this.formatDateTimeMHS(maxTime)
          // console.log(maxTime)
        }
      })
    },
    //移出文件事件
    handleRemove (file, fileList) {
      this.fileList = fileList
      console.log(`文件${file.name}移出`)
    },
    //文件列表发生变化
    handleFileChange (file, fileList) {
      let size10M = file.size / 1024 / 1024 < 10
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过 10MB!');
        this.$refs['uploadFile'].handleRemove(file);
      } else {
        this.fileList = fileList
      }
    },
    //获取上传文件的id
    async getFileId () {
      let promisesList = []
      let dataList = []
      this.fileList.forEach(item => {
        let fd = new FormData();
        fd.append("file", item.raw)
        promisesList.push(demoApi.fileUpload(fd))
      })
      await Promise.all(promisesList).then(resList => {
        resList.forEach(res => {
          dataList.push(res.data)
        })
      }).catch(err => {
        console.log('出错了', err)
      });
      return dataList
    },
    //获取添加表单下拉项
    queryEssentialData () {
      Promise.all([
        BatchApi.queryByCondition(),  //获取批次
        StaffApi.queryByCondition()  //获取员工
      ]).then(resList => {
        this.batchList = resList[0].data;
        this.staffList = resList[1].data;
        console.log('批次:', this.batchList)
        console.log('员工:', this.staffList)
      }).catch(err => {
        console.log(err)
      })
    },
    //保存 nowChanceStau判断添加/编辑
    async save (formData) {
      if (!this.fileList.length) {
        this.$message('请上传检验报告!')
        return
      }
      this.$refs[formData].validate(async (valid) => {
        this.formData.reportFileIdList = await this.getFileId();
        this.formData.productionBatchDTO && (this.formData.productionBatchId = this.formData.productionBatchDTO.productionBatchId || [])
        if (valid) {
          if (this.nowChanceStau == 'add') {
            inspectionReportApi.addOMS(this.formData).then(res => {
              if (res.success) {
                this.close()
                this.$message.success("添加成功！");
              } else {
                this.$message("操作失败");
              }
            });
          } else if (this.nowChanceStau == 'edit') {
            inspectionReportApi.editOMS(this.formData).then(res => {
              console.log(res)
            });
          }
        } else {
          return false;
        }
      });
    },
    //关闭
    close () {
      this.$emit("closeDialog");
    },
    //取消
    cancel () {
      this.$emit("cancelDialog");
      this.$refs['ruleForm'].resetFields()
    }
  }
};
</script>

<style lang="scss" scoped>
.rightTableData {
  ::v-deep .el-form-item__error {
    top: calc(100% - 5px);
  }

  ::v-deep .el-form-item {
    height: 40px;
    margin-bottom: 0;

    .el-input__inner {
      height: 40px;
    }
  }

  ::v-deep .cell {
    overflow: visible;
  }

  // ::v-deep .el-input__inner{

  // }
}

.addInfo {
  width: 100%;
}

::v-deep .el-table {
  position: relative;
}

::v-deep .tab-select {
  margin: 0 !important;
}
</style>
